import Taro from "@tarojs/taro"
import {baseURLAddress} from './baseURL'
import {setToken, getToken, showToast} from "../common"

export default class BaseRequest {
  constructor(baseURL?: string) {
    baseURL = baseURL || baseURLAddress
    let that: any = this
    that.$http = (
      url: string,
      params: object,
      ContentType = 'application/json',
      method = 'GET',
      config: any
    ) => {
      return new Promise((resolve, reject) => {
        const interceptor = function (chain: any) {
          let requestParams = chain.requestParams || ''
          let token = Taro.getStorageSync('userToken') || ''
          if (token) {
            Object.assign(requestParams.header, config.header)
            requestParams.header['Authorization'] = token
          }
          return chain.proceed(requestParams)
            .then((res: any) => {
              return res
            })
        }
        Taro.addInterceptor(interceptor)
        Taro.request({
          url: `${baseURL + url}`,
          method,
          data: params,
          header: {
            'Content-Type': ContentType
          },
          ...config
        }).then(res => {
          if (res.data.code === 1) {
            resolve(res.data)
          } else if (res.data.errCode === 10010 || res.data.errCode === 10005) {
            // token失效时reLaunch页面
            if (getToken()) {
              setToken("")
            }
            showToast(res.data.msg)
            Taro.reLaunch({
              url: `/pages/user/index`
            })
          } else {
            reject(res.data)
          }
        }).catch(error => {
          reject({error, msg: '网络开小差，请稍后再试'})
        })
      }).catch(e => {
          showToast(e.msg)
        }
      )
    }
  }

  post(url: string, params = {}, config = {}) {
    let that: any = this;
    return that.$http(url, params, 'application/json', 'POST', config)
  }

  get(url: string, params = {}, config = {}) {
    let that: any = this;
    return that.$http(url, params, 'application/json', 'GET', config)
  }

  getForm(url: string, params = {}, config = {}) {
    let that: any = this;
    return that.$http(url, params, 'application/x-www-form-urlencoded', 'GET', config)
  }

  postForm(url: string, params = {}, config = {}) {
    let that: any = this;
    return that.$http(url, params, 'application/x-www-form-urlencoded', 'POST', config)
  }
}
